package com.ysy.common.exception;

import com.ysy.common.resp.ResultData;
import com.ysy.common.resp.ReturnCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassDescription: 全局异常拦截器
 * @Author:姚斯羽
 * @Create:2025/3/12 13:58
 **/
@Slf4j
@ControllerAdvice
@Order(99)
public class GlobalExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultData<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {

        return ResultData.fail(ReturnCodeEnum.RC205.getCode() ,e.getBindingResult().getFieldError().getDefaultMessage());
    }
    /**
     * 默认全局异常处理。
     * @param e the e
     * @return ResultData
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> exception(Exception e) {
        System.out.println("----come in GlobalExceptionHandler");
        log.error("全局异常信息exception:{}", e.getMessage(), e);
        return ResultData.fail(ReturnCodeEnum.RC500.getCode(),e.getMessage());
    }
}
